// 缓存键名
const CACHE_KEY = 'bookmarks_cache';

// 获取缓存数据
function getCachedBookmarks() {
    const cachedData = localStorage.getItem(CACHE_KEY);
    if (cachedData) {
        return JSON.parse(cachedData);
    }
    return null;
}

// 保存缓存数据
function saveCachedBookmarks(bookmarks) {
    localStorage.setItem(CACHE_KEY, JSON.stringify(bookmarks));
}

// 获取收藏夹数据（优先使用缓存）
function fetchBookmarks() {
    const cachedBookmarks = getCachedBookmarks();
    if (cachedBookmarks) {
        console.log("使用缓存数据");
        return Promise.resolve(cachedBookmarks);
    }

    return new Promise((resolve) => {
        chrome.bookmarks.getTree((bookmarkTreeNodes) => {
            const bookmarks = parseBookmarks(bookmarkTreeNodes);
            saveCachedBookmarks(bookmarks); // 保存缓存
            resolve(bookmarks);
        });
    });
}

// 解析收藏夹数据
function parseBookmarks(bookmarkTreeNodes) {
    const bookmarks = []; // 使用数组存储书签数据

    // 递归遍历收藏夹树
    const traverse = (nodes, parentPath = []) => {
        nodes.forEach((node) => {
            if (node.children) {
                // 这是一个文件夹，更新父文件夹路径
                const currentPath = [...parentPath, node.title]; // 将当前文件夹名添加到路径中
                traverse(node.children, currentPath); // 递归遍历子节点
            } else if (node.url) {
                // 这是一个书签链接，保留完整的父文件夹路径
                bookmarks.push({
                    path: parentPath, // 父文件夹路径（数组形式）
                    name: node.title,
                    url: node.url,
                });
            }
        });
    };

    traverse(bookmarkTreeNodes); // 开始遍历
    console.log("解析后的 bookmarks:", bookmarks); // 打印解析后的数据
    return bookmarks;
}

// 渲染收藏夹数据
function renderBookmarks(bookmarks) {
    console.log("bookmarks:", bookmarks); // 打印 bookmarks 的值
    console.log("bookmarks 类型:", typeof bookmarks); // 打印 bookmarks 的类型

    if (!Array.isArray(bookmarks)) {
        console.error("bookmarks 不是数组:", bookmarks);
        return;
    }

    const mainContent = document.getElementById('main-content');
    if (!mainContent) {
        console.error("未找到 #main-content 元素");
        return;
    }
    mainContent.innerHTML = ''; // 清空容器

    // 按层级分组
    const groupedBookmarks = {};
    bookmarks.forEach((bookmark) => {
        let currentGroup = groupedBookmarks;

        // 遍历路径层级
        bookmark.path.forEach((folder, index) => {
            if (!currentGroup[folder]) {
                currentGroup[folder] = { _bookmarks: [] };
            }
            currentGroup = currentGroup[folder];
        });

        // 将书签添加到当前层级
        currentGroup._bookmarks.push(bookmark);
    });

    // 渲染分组
    renderGroup(groupedBookmarks, mainContent);

    // 初始化懒加载
    initLazyLoad();
}

// 递归渲染分组
function renderGroup(group, container, level = 0) {
    for (const folder in group) {
        if (folder === '_bookmarks') continue; // 跳过书签数据

        // 创建分组容器
        const groupCard = document.createElement('div');
        groupCard.className = `group-card lazy`; // 添加 lazy 类
        groupCard.dataset.bookmarks = JSON.stringify(group[folder]._bookmarks || []); // 存储书签数据

        // 分组标题
        const groupTitle = document.createElement('div');
        groupTitle.className = 'group-title';

        // 根据层级设置标题标签
        const headingTag = `h${Math.min(level + 1, 6)}`; // 最多支持 h6
        groupTitle.innerHTML = `<${headingTag}>${folder}</${headingTag}>`;
        groupCard.appendChild(groupTitle);

        // 卡片容器
        const cardContainer = document.createElement('div');
        cardContainer.className = 'card-container';
        groupCard.appendChild(cardContainer);

        container.appendChild(groupCard);

        // 渲染子分组
        renderGroup(group[folder], groupCard, level + 1);
    }
}

// 搜索功能
function searchBookmarks(query, bookmarks) {
    const results = bookmarks.filter((bookmark) => {
        return bookmark.name.toLowerCase().includes(query.toLowerCase()) || bookmark.url.toLowerCase().includes(query.toLowerCase());
    });

    return results;
}

// 显示搜索结果
function showSearchResults(results) {
    const searchResults = document.getElementById('search-results');
    searchResults.innerHTML = '';

    if (results.length === 0) {
        searchResults.innerHTML = '<p>未找到匹配的书签。</p>';
        return;
    }

    results.forEach((bookmark) => {
        const resultItem = document.createElement('div');
        resultItem.className = 'search-result-item';
        resultItem.innerHTML = `
            <p class="search-result-title">${bookmark.name}</p>
            <a href="${bookmark.url}" target="_blank" class="search-result-link">${bookmark.url}</a>
        `;
        searchResults.appendChild(resultItem);
    });
}

// 初始化搜索功能
function initSearch(bookmarks) {
    const searchBox = document.getElementById('search-box');
    const searchOverlay = document.getElementById('search-overlay');

    searchBox.addEventListener('input', (event) => {
        const query = event.target.value.trim();

        if (query) {
            const results = searchBookmarks(query, bookmarks);
            showSearchResults(results);
            searchOverlay.style.display = 'flex';
        } else {
            searchOverlay.style.display = 'none';
        }
    });

    // 点击遮罩层外部关闭搜索
    searchOverlay.addEventListener('click', (event) => {
        if (event.target === searchOverlay) {
            searchOverlay.style.display = 'none';
        }
    });
}



// 懒加载配置
const lazyLoadConfig = {
    rootMargin: '0px',
    threshold: 0.1, // 当元素 10% 可见时触发加载
};

// 初始化懒加载
function initLazyLoad() {
    const lazyGroups = document.querySelectorAll('.group-card.lazy');
    const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                const groupCard = entry.target;
                groupCard.classList.remove('lazy');
                renderCards(groupCard);
                observer.unobserve(groupCard); // 停止观察已加载的元素
            }
        });
    }, lazyLoadConfig);

    lazyGroups.forEach((group) => observer.observe(group));
}

// 渲染卡片
function renderCards(groupCard) {
    const cardContainer = groupCard.querySelector('.card-container');
    const bookmarks = JSON.parse(groupCard.dataset.bookmarks);

    // 分块加载书签
    renderBookmarksInChunks(bookmarks, cardContainer);
}

// 分块加载配置
const CHUNK_SIZE = 20; // 每次加载 20 个书签

// 分块渲染书签
function renderBookmarksInChunks(bookmarks, container) {
    let index = 0;

    const renderChunk = () => {
        const chunk = bookmarks.slice(index, index + CHUNK_SIZE);
        chunk.forEach((bookmark) => {
            const card = document.createElement('div');
            card.className = 'card';
            card.innerHTML = `
                <div class="card-content">
                    <p class="card-title">${bookmark.name}</p>
                    <a href="${bookmark.url}" target="_blank" class="card-button">访问</a>
                </div>
            `;
            container.appendChild(card);
        });

        index += CHUNK_SIZE;
        if (index < bookmarks.length) {
            requestAnimationFrame(renderChunk); // 继续加载下一块
        }
    };

    renderChunk();
}

// 初始化
fetchBookmarks().then((bookmarks) => {
    renderBookmarks(bookmarks);
    initSearch(bookmarks);
});